//
//  BaseRequest.m
//  YYBG_IOS
//
//  Created by wyl on 2017/2/22.
//  Copyright © 2017年 wyl. All rights reserved.
//

#import "BaseRequest.h"

@implementation BaseRequest


+(AFHTTPSessionManager *) getAFHTTPRequestOperationManagerWithUrl:(NSString *)url method:(NSString *) method paramType:(PARAM_TYPE) paramType{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    manager.requestSerializer  = [AFHTTPRequestSerializer serializer];
//     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//    AFJSONResponseSerializer *response = (AFJSONResponseSerializer *)manager.responseSerializer;
//    response.removesKeysWithNullValues = YES;
    return manager;
}



/**
 *  对象转jsonString
 *
 *  @param object 对象
 *
 *  @return jsonString
 */
+ (NSString*) stringWithObject:(id)object {
    
    if ([object isKindOfClass:[NSDictionary class]] || [object isKindOfClass:[NSArray class]]) {
        NSString *jsonString = nil;
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:&error];
        if (! jsonData) {
            NSLog(@"Got an error: %@", error);
        } else {
            jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
        return jsonString;
        
    } else {
        return object;
    }
    
}

/**
 *  post方法 (不带文件上传功能)
 *
 *  @param url          url地址
 *  @param params       请求参数:NSDictionary或NSArray类型，无参数时传入nil
 *  @param type         参数模式，表单模式或body模式
 *  @param cacheSuccess 缓存回调block(主线程)
 *  @param success      成功回调block(主线程)
 *  @param failure      失败回调block(主线程)
 */
+(void) post:(NSString *) url parameters:(id) params  paramType:(PARAM_TYPE) type  success:(loadSuccess) success failure:(loadFailure) failure{
    
    NSString *METHOD_POST = @"POST";
    AFHTTPSessionManager *manager = [self getAFHTTPRequestOperationManagerWithUrl:url method:METHOD_POST paramType:type];
    [manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
    NSLog(@"############post_url #############%@",url);
    NSLog(@"############post_参数 #############%@",params);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"############post_数据返回 #############%@",responseObject);
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}




/**
 *  get方法
 *
 *  @param url          url地址
 *  @param cacheSuccess 缓存回调block(主线程)
 *  @param success      成功回调block(主线程)
 *  @param failure      失败回调block(主线程)
 */
+(void)  get:(NSString *) url success:(loadSuccess) success failure:(loadFailure) failure{
    
    NSString *METHOD_GET = @"GET";
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //处理缓存
    NSLog(@"############get_url #############%@",url);
    AFHTTPSessionManager *manager = [self getAFHTTPRequestOperationManagerWithUrl:url method:METHOD_GET paramType:PARAM_TYPE_BODY];
  
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//          NSLog(@"############get_数据返回 #############%@",responseObject);
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            NSLog(@"访问失败，错误信息:%@",error);
            failure(error);
        }
    }];
}

+(void) put:(NSString *)url parameters:(id)params success:(loadSuccess)success failure:(loadFailure)failure {
    
    AFHTTPSessionManager *manager = [self getAFHTTPRequestOperationManagerWithUrl:url method:@"PUT" paramType:PARAM_TYPE_BODY];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager PUT:url parameters:params success:^(NSURLSessionDataTask *operation, id responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        
        if (failure) {
            failure(error);
        }
    }];
}

+(void) delete:(NSString *)url parameters:(id) params  success:(loadSuccess)success failure:(loadFailure)failure {
    AFHTTPSessionManager *manager = [self getAFHTTPRequestOperationManagerWithUrl:url method:@"DELETE"  paramType:PARAM_TYPE_BODY];
    
    [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    [manager DELETE:url parameters:params success:^(NSURLSessionDataTask *operation, id responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        
        if (failure) {
            failure(error);
        }
    }];
    
}

+(void) post:(NSString *)url imageName:(NSString *)imageName parameters:(id)params paramType:(PARAM_TYPE) type image:(UIImage *)image success:(loadSuccess)success failure:(loadFailure)failure {
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    NSLog(@"############post_url #############%@",url);
    NSLog(@"############post_参数 #############%@",params);
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data ;
        if (UIImagePNGRepresentation(image)) {
            //返回为png图像。
            data = UIImagePNGRepresentation(image);
            NSString *nameFile  = [NSString stringWithFormat:@"%@.png",imageName];
            [formData appendPartWithFileData:data name:@"upload" fileName:nameFile  mimeType:@"image/png"];
        }else {
            //返回为JPEG图像。
            data = UIImageJPEGRepresentation(image,1);
            NSString *nameFile  = [NSString stringWithFormat:@"%@.jpg",imageName];
            [formData appendPartWithFileData:data name:@"upload" fileName:nameFile  mimeType:@"image/jpeg"];
        }
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject) {
//         NSLog(@"############post_数据返回 #############%@",responseObject);
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable operation, NSError * _Nonnull error) {
        
        if (failure) {
            failure(error);
        }
    }];
}


+(void) postImages:(NSString *)url imageName:(NSString *)imageName parameters:(id)params paramType:(PARAM_TYPE) type image:(NSArray *)image success:(loadSuccess)success failure:(loadFailure)failure {
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    NSLog(@"############post_url #############%@",url);
    NSLog(@"############post_参数 #############%@",params);
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (image) {
            for (int i = 0 ; i<image.count; i++) {
                
                NSData *imageData = image[i];
                UIImage *image = [UIImage imageWithData: imageData];
                if (UIImagePNGRepresentation(image)) {
                   
                    NSString *nameFile  = [NSString stringWithFormat:@"%@.png",imageName];
                    NSString *fileName = [NSString stringWithFormat:@"upload[%d]",i+1];
                    [formData appendPartWithFileData:imageData name:fileName fileName:nameFile  mimeType:@"image/png"];
                }else {
                    NSString *nameFile  = [NSString stringWithFormat:@"%@.jpg",imageName];
                    NSString *fileName = [NSString stringWithFormat:@"upload[%d]",i+1];
                    [formData appendPartWithFileData:imageData name:fileName fileName:nameFile  mimeType:@"image/jpeg"];
                }
             
                
              
            }
        }
       
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//         NSLog(@"############post_数据返回 #############%@",responseObject);
        if (success) {
            success(responseObject);
        }else{
            failure(nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

@end
